var AUDIO_SERVICE_URL = "http://localhost:1374/Service/service.svc/GetAudioData";
var EXTRACT_SERVICE_URL = "http://localhost:1374/Service/service.svc/GetWebPageData";

var sentences;
var LENGTH;
var audios = new Array();
var currentAudioIndex = 0;
var MAX = 2;
var MUTE = false;
var VOLUME = 1;

// Service trich xuat noi dung trang web
function extractService(value){
	$.ajax({
	    url: EXTRACT_SERVICE_URL,
		dataType: "jsonp",
		data: { url: value },
		success: function(data) {
			// Chuyen doi noi dung trang web hien tai
			document.documentElement.innerHTML = data.content;
			// Them vao cac phan tu dieu khien play
			addHTMLAudioElement();
		}
	});
}

// Xy ly bat phim tat
document.addEventListener("keydown",keyProcessing,false);
function keyProcessing(e){
if((e.altKey)&&(e.keyCode==KeyEvent.DOM_VK_R)){
		getAudio();
	}
}

// Them vao cac phan tu dieu khien play
function addHTMLAudioElement(){
	var body = document.getElementsByTagName('BODY').item(0);
	
	var t8=document.createElement("input");
	t8.setAttribute("type","button");
	t8.setAttribute("value","Tắt âm");
	t8.setAttribute("onclick", "mute()");
	body.insertBefore(t8, body.firstChild);
	
	var t7=document.createElement("input");
	t7.setAttribute("type","button");
	t7.setAttribute("value","Giảm âm");
	t7.setAttribute("onclick", "decreaseVolume()");
	body.insertBefore(t7, body.firstChild);
	
	var t6=document.createElement("input");
	t6.setAttribute("type","button");
	t6.setAttribute("value","Tăng âm");
	t6.setAttribute("onclick", "increaseVolume()");
	body.insertBefore(t6, body.firstChild);
	
	var t5=document.createElement("input");
	t5.setAttribute("type","button");
	t5.setAttribute("value","Trước 2 giây");
	t5.setAttribute("onclick", "previousSecond()");
	body.insertBefore(t5, body.firstChild);
	
	var t4=document.createElement("input");
	t4.setAttribute("type","button");
	t4.setAttribute("value","Câu sau");
	t4.setAttribute("onclick", "nextSentence()");
	body.insertBefore(t4, body.firstChild);
	
	var t3=document.createElement("input");
	t3.setAttribute("type","button");
	t3.setAttribute("value","Câu trước");
	t3.setAttribute("onclick", "previousSentence()");
	body.insertBefore(t3, body.firstChild);
	
	var t2=document.createElement("input");
	t2.setAttribute("type","button");
	t2.setAttribute("value","Đọc/Dừng đọc");
	t2.setAttribute("onclick", "pause(true)");
	body.insertBefore(t2, body.firstChild);
	
	var t1=document.createElement("input");
	t1.setAttribute("type","button");
	t1.setAttribute("value","Lấy về âm thanh");
	t1.setAttribute("onclick", "getAudio()");
	body.insertBefore(t1, body.firstChild);
}

// Ham dieu khien dung choi
function pause(switchStatus){
	if (audios[currentAudioIndex] != null){
		if (switchStatus){
			if (audios[currentAudioIndex].paused) 
				audios[currentAudioIndex].play(); 
			else 
				audios[currentAudioIndex].pause();
		} else
			audios[currentAudioIndex].pause();
	}
}

//Ham dieu khien choi cau sau
function nextSentence(){
	// Dung audio dang play
	pause(false);
	
	// Thay doi chi so
	if (currentAudioIndex < LENGTH-1)
		currentAudioIndex++;
	
	// Chua co du lieu thi lay ve
	if (audios[currentAudioIndex] == null) {
	    audioService(sentences[currentAudioIndex], currentAudioIndex);
	}
	else {
	    // Play
	    playAudio(currentAudioIndex);
	}
}

// Ham dieu khien choi cau truoc
function previousSentence(){
	// Dung audio dang play
	pause(false);
	
	// Thay doi chi so
	if (currentAudioIndex > 0)
		currentAudioIndex --;
	
	// Chua co du lieu thi lay ve
	if (audios[currentAudioIndex] == null) {
	    audioService(sentences[currentAudioIndex], currentAudioIndex);
	}
	else {
	    // Play
	    playAudio(currentAudioIndex);
	}
}


// Ham dieu khien choi 2 giay truoc do
function previousSecond(){
	audios[currentAudioIndex].currentTime -= 2;
}

// Tat am
function mute(){
	audios[currentAudioIndex].muted = !audios[currentAudioIndex].muted;
	MUTE = audios[currentAudioIndex].muted; 
}

// Tang am
function increaseVolume(){
	audios[currentAudioIndex].volume += 0.2;
	VOLUME = audios[currentAudioIndex].volume;
}

// Giam am
function decreaseVolume(){
	audios[currentAudioIndex].volume -= 0.2;
	VOLUME = audios[currentAudioIndex].volume;
}


// Reset hoac Start viec lay ve audio
function getAudio(){
	// Neu dang play thi phai dung lai
	pause(false);
	
	// Lay ra cac cau, khoi tao lai cac ham so
	sentences = splitParagraph($("P").text());
	LENGTH = sentences.length;
	audios = new Array();
	currentAudioIndex = 0;
	
	//Lay du lieu cua cau dau tien
	audioService(sentences[0],0);
}

// Service text to speech
function audioService(value, index) {

    var extension;
    if ($.browser.mozilla)
        extension = "wav";
    else
        extension = "mp3";

    $.ajax({
        url: AUDIO_SERVICE_URL,
        dataType: "jsonp",
        data: { voiceIndex: 1, extension: extension, text: value },
        success: function (data) {
            var bytes;
            if (extension == "wav")
                bytes = "data:audio/wav;base64," + data.audioBytes;
            else
                bytes = "data:audio/mpeg;base64," + data.audioBytes;

            var audio = new Audio();
            audio.setAttribute("src", bytes);
            audios[index] = audio;

            // Lay xong audio, kiem tra co thoa man dieu kien play khong & play
            if (index == currentAudioIndex) {
                playAudio(index);
            }
        }
    });
}
	
function playAudio(index) {
    for (var i = 0; i < audios.length; ++i)
    {
        if (audios[i] != null)
            audios[i].pause();
    }
	audios[index].load();
	audios[index].play();
	// Thiet lap volume
	audios[index].muted = MUTE;
	audios[index].volume = VOLUME;
	audios[index].addEventListener('ended', 
		function(){							
			// Play xong moi xu ly
			if (currentAudioIndex < LENGTH-1){
				currentAudioIndex++;
				if (audios[currentAudioIndex] != null)
					playAudio(currentAudioIndex);
			}	
			else
				currentAudioIndex = 0;
		}
	, false
	);
	
	// Kiem tra MAX cau sau, neu chua co du lieu thi lay ve
	for (var i = index; i<=index+MAX && i<LENGTH; i++){
		if (audios[i] == null)
			audioService(sentences[i], i);
	}

	// Kiem tra MAX cau truoc, neu chua co du lieu thi lay ve
	for (var i = index; i<=index-MAX && i>=0; i--){
		if (audios[i] == null)
			audioService(sentences[i], i);
	}
}

// Tien ich thay the replaceAll, nhanh hon regular expression
String.prototype.replaceAll = function(token, newToken, ignoreCase) {
    var str, i = -1, _token;
    if((str = this.toString()) && typeof token === "string") {
        _token = ignoreCase === true? token.toLowerCase() : undefined;
        while((i = (
            _token !== undefined? 
                str.toLowerCase().indexOf(
                            _token, 
                            i >= 0? i + newToken.length : 0
                ) : str.indexOf(
                            token,
                            i >= 0? i + newToken.length : 0
                )
        )) !== -1 ) {
            str = str.substring(0, i)
                    .concat(newToken)
                    .concat(str.substring(i + token.length));
        }
    }
	return str;
};

// Ham nay dung de phan tich mot doan van thanh cac cau ngan
function splitParagraph(text){
    var reg = /[.!?;]/g ;   // Cac dau phan cach cau
    var textArr = text.split(reg); // Tach doan van thanh cac cau, luu vao mang textArr
    
    // Duyet mang cac cau thu duoc, cau nao dai phai tach tiep thanh cac cau ngan hon 90 ki tu
    var textResult = new Array();
    var i = 0;
    for(i = 0; i < textArr.length; i++){
        // chuan hoa str truoc: loai bo whitespace truoc va sau cau
        var str = trim(textArr[i]);
        
        // Phan tich chuoi
        if(str.length == 0){
            // do nothing with str
        }else if(str.length > 0 && str.length <= 400){
            textResult.push(str);
        } else if(str.length > 400){ // tach str thanh nhieu doan ma kich thuoc nho hon 100 ki tu
            textResult = textResult.concat(splitLongStr(str));
        }
    }
    
    return textResult;
}

// Chuan hoa co ban chuoi str
function trim(str){
    var ltrimpatt = /^\s*/g;
    var rtrimpatt = /\s*$/g;
    str = str.replace(ltrimpatt,'');
    str = str.replace(rtrimpatt,'');
    return str;
}

// Ham tach mot cau dai thanh nhieu doan sao cho dam bao ngu phap khong bi tach tu
function splitLongStr(str){
    var result = new Array();
    while(str.length > 400){
        i=100;
        while(str.charAt(i) != ' ') i--;
        token = str.substring(0,i);
        result.push(token);
        str = str.substring(i+1);
    }
    result.push(str);
    return result;
}